//
//  SearchView.swift
//  WZApp
//
//  Created by evol on 2018/6/28.
//  Copyright © 2018年 evol. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift
import RxDataSources
import SwiftyJSON

let kELSearchView_contentWidth: CGFloat = 220.0
let kELSearchView_contentHeight: CGFloat = 250.0

class ELSearchView: UIButton {
    
    let disposeBag = DisposeBag()

    var viewModel: ELSearchViewModel!

    var searchButton: UIButton!

    var textField: UITextField!

    var tableView: UITableView!
    
    
    init(_ viewModel: ELSearchViewModel, searchButton:UIButton) {
        super.init(frame:.zero)
        self.viewModel = viewModel

        setCloseEvent()

        textField = UITextField()
        textField.backgroundColor = UIColor.black.withAlphaComponent(0.4)
        textField.font = UIFont.systemFont(ofSize: 15)
        textField.textColor = .black
        textField.layer.cornerRadius = 3.0
        textField.layer.masksToBounds = true
        textField.attributedPlaceholder = NSAttributedString(string: "点击输入", attributes: [NSAttributedStringKey.foregroundColor: UIColor.hexColor("bbbbbb")])
        let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 14, height: 0))
        textField.leftView = leftView
        textField.leftViewMode = .always
        self.addSubview(textField)

        let frame = searchButton.frame
        textField.snp.makeConstraints { (make) in
            make.centerY.equalTo(frame.midY)
            make.right.equalTo( frame.maxX - SCREEN_WIDTH + 5 )
            make.height.equalTo(frame.height + 8)
            make.width.equalTo(0)
        }
        //textfield 的文字事件传递给 ViewModel
        viewModel.searchInput = textField.rx.text.orEmpty.asObservable()

        tableView = UITableView()
        tableView.backgroundColor = UIColor.white.withAlphaComponent(0.5)
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 44.00
        tableView.register(ELSearchTableViewCell.self, forCellReuseIdentifier: "Cell")
        addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(textField.snp.bottom)
            make.width.equalTo(kELSearchView_contentWidth)
            make.right.equalTo(textField)
            make.height.equalTo(0)
        }

        viewModel.datas?.asObservable().bind(to: tableView.rx.items){ (tv, row ,element) in
            let cell = tv.dequeueReusableCell(withIdentifier: "Cell") as! ELSearchTableViewCell
            cell.model = element
            cell.button.rx.tap.subscribe(onNext: {
                print("导航去这里:",element.name ?? "")
            }).disposed(by:cell.disposeBag)
            return cell
        }.disposed(by: disposeBag)

        tableView.rx.modelSelected(ELTagModel.self).subscribe(onNext: { (model) in
            viewModel.locationCommand.onNext(model)
        }).disposed(by:disposeBag)

        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: {
            self.showAnimation()
        })
    }
    
    func showAnimation() -> Void {

        UIView.animate(withDuration: 0.25, animations: { [weak self] in
            self?.textField.snp.updateConstraints { (make) in
                make.width.equalTo(kELSearchView_contentWidth.scaleForScreen)
            }
            self?.layoutIfNeeded()
        }) { (completed) in
            self.tableView.snp.updateConstraints({ (make) in
                make.height.equalTo(kELSearchView_contentHeight)
            })
            UIView.animate(withDuration: 0.25, animations: {
                self.layoutIfNeeded()
            })
        }
    }

    func hideAnimation(hideSearchButton: Bool) -> Void {
        UIView.animate(withDuration: 0.25, animations: {
            self.tableView.snp.updateConstraints({ (make) in
                make.height.equalTo(0)
            })
            self.layoutIfNeeded()
        }) { (completed) in
            if completed {
                self.viewModel.closeCommand.onNext(hideSearchButton)
                UIView.animate(withDuration: 0.25, animations: {
                    self.textField.snp.updateConstraints({ (make) in
                        make.width.equalTo(0)
                    })
                    self.layoutIfNeeded()
                }) { (completed) in
                    self.removeFromSuperview()
                }
            }
        }
    }

    
    func setCloseEvent() -> Void {
        self.rx.tap.subscribe(onNext:{ [weak self] _ in
            self?.hideAnimation(hideSearchButton: false)
        }).disposed(by: disposeBag)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
